package com.itaming.lycheeframework.security.authorization;

import com.itaming.lycheeframework.security.exception.AccessDeniedException;
import com.itaming.lycheeframework.support.utils.ClassUtil;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.reflect.Method;

/**
 * 权限验证切面类
 *
 * @author A.Ming
 */
@Aspect
@RequiredArgsConstructor
public class PermissionAspect {

    /**
     * 授权检查器
     */
    private final AuthorizationChecker authorizationChecker;

    /**
     * 验证
     *
     * @param joinPoint 切点
     * @return 原始方法返回值
     * @throws Throwable
     */
    @Around("@within(com.itaming.lycheeframework.security.authorization.Permission)" +
        " || @annotation(com.itaming.lycheeframework.security.authorization.Permission)")
    public Object permission(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取方法
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();

        // 获取方法上的权限注解
        Permission annotation = ClassUtil.getAnnotation(method, Permission.class);

        // 验证权限
        String[] permissions = annotation.value();

        // 验证
        switch (annotation.type()) {
            case AND -> {
                if (!authorizationChecker.hasAllPermission(permissions)) {
                    throw new AccessDeniedException();
                }
            }
            case OR -> {
                if (!authorizationChecker.hasAnyPermission(permissions)) {
                    throw new AccessDeniedException();
                }
            }
        }

        return joinPoint.proceed();
    }

}
